package servlet;

import domain.Comments;
import domain.News;
import domain.Topic;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import services.CommentsServicesImpl;
import services.NewsServicesImpl;
import services.TopicServicesImpl;
import services.UserServicesImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class AdminNewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        UserServicesImpl userServices = new UserServicesImpl();
        TopicServicesImpl topicServices = new TopicServicesImpl();
        NewsServicesImpl newsServices = new NewsServicesImpl();
        CommentsServicesImpl commentsServices = new CommentsServicesImpl();
        try {
            //获取方法名
            String method = request.getParameter("method");
            if (method == null) {
                System.out.println("参数错误");
            } else if (method.equals("deleteTopic")) {//删除分类
                String tid = request.getParameter("tid");
                String tname = request.getParameter("tname");
                //获取该分类下是否有新闻，如果有则不能删除分类
                if (0 == newsServices.countNews(Integer.parseInt(tid))) {
                    int count = topicServices.deleteTopicByTid(Integer.parseInt(tid));
                    if (count > 0) {
                        System.out.println("有" + count + "个分类被删除:" + tname);
                        request.setAttribute("deleteTopic_msg", tname + "分类删除成功");
                    } else {
                        System.out.println(tname + "分类已不存在，删除失败");
                        request.setAttribute("deleteTopic_msg", tname + "分类已不存在，删除失败");
                    }
                } else {
                    request.setAttribute("deleteTopic_msg", tname + "分类中存在新闻，不能删除");
                }
                request.getRequestDispatcher("/adminServlet/news?method=refreshTopic").forward(request, response);
            } else if (method.equals("refreshTopic")) {//刷新分类页面
                //获取所有topic
                List<Topic> topicList = topicServices.getAllTopic();
                //将topic列表存入request域
                request.setAttribute("topicList", topicList);
                request.getRequestDispatcher("/newspages/admin.jsp").forward(request, response);
            } else if (method.equals("modifyTopic")) {//修改分类名称
                //获取需要修改的分类的tid
                String tid = request.getParameter("tid");
                //获取用户输入的分类名
                String tname = request.getParameter("tname");
                int count = topicServices.modifyTopicByTid(Integer.parseInt(tid), tname);
                if (count > 0) {
                    System.out.println("有" + count + "个分类被修改:" + tid + "---" + tname);
                    request.setAttribute("modifyTopic_msg", "分类名称修改成功");
                } else {
                    request.setAttribute("modifyTopic_msg", "分类名称修改失败");
                }
                request.getRequestDispatcher("/newspages/topic_modify.jsp").forward(request, response);
            } else if (method.equals("addTopic")) {//添加分类
                String tname = request.getParameter("tname");
                int count = topicServices.addTopic(tname);
                if (count > 0) {
                    System.out.println("有" + count + "个分类被添加:" + tname);
                    request.setAttribute("addTopic_msg", "分类添加成功:" + tname);
                } else {
                    System.out.println("分类添加失败");
                    request.setAttribute("addTopic_msg", "分类添加失败");
                }
                request.getRequestDispatcher("/newspages/topic_add.jsp").forward(request, response);
            } else if (method.equals("getNewsByPage")) {//分页获取新闻
                String pageNo = request.getParameter("pageNo");
                String size = request.getParameter("size");
                String tid = request.getParameter("tid");
                //进入新闻服务层
                List<News> newsList = newsServices.getNewsByNumber(Integer.parseInt(tid), Integer.parseInt(pageNo), Integer.parseInt(size));
                //获取该类型的新闻有多少条，计算需要多少页来展示
                int countNews = newsServices.countNews(Integer.parseInt(tid));
                int totalPages = (int) Math.ceil(countNews / Double.parseDouble(size));
                //将新闻列表、获取到的页码、每页条数、获取具体新闻类型存入request域
                request.setAttribute("newsList", newsList);
                request.setAttribute("pageNo", pageNo);
                request.setAttribute("totalPages", totalPages);
                request.setAttribute("tid", tid);
                //跳转
                request.getRequestDispatcher("/newspages/admin.jsp").forward(request, response);
            } else if (method.equals("getAllTopic")) {//在新闻添加页面获取所有新闻类型
                //获取所有topic，显示新闻类型
                List<Topic> allTopic = topicServices.getAllTopic();
                //topic列表存入request域
                request.setAttribute("topicList", allTopic);
                request.getRequestDispatcher("/newspages/news_add.jsp").forward(request, response);
            } else if (method.equals("showNewsDetailsByNid")) {//获取新闻的详细信息展示在编辑新闻页面上
                //获取需要修改的新闻nid
                String nid = request.getParameter("nid");
                //获取所有topic，用于所有显示新闻类型
                List<Topic> allTopic = topicServices.getAllTopic();
                //topic列表存入request域
                request.setAttribute("topicList", allTopic);
                //根据nid进入服务层获取News对象
                News news = newsServices.getNewsDetailsByNid(Integer.parseInt(nid));
                //将News对象存入request域
                request.setAttribute("news", news);
                //获取评论
                //1.进入服务层获取评论对象
                List<Comments> commentsByCnid = commentsServices.getCommentsByCnid(Integer.parseInt(nid));
                //2.将评论对象存入request域
                request.setAttribute("comments", commentsByCnid);
                //跳转到新闻编辑页面
                request.getRequestDispatcher("/newspages/news_modify.jsp").forward(request, response);
            } else if (method.equals("modifyNews")) {//修改新闻内容
                //获取所有参数
                Map parameterMap = request.getParameterMap();
                //封装新的News对象
                News newsModified = new News();
                BeanUtils.populate(newsModified, parameterMap);
                //添加最后一次修改时间到News对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = sdf.format(new Date());
                newsModified.setNmodifyDate(date);
                //进入服务层修改新闻
                int count = newsServices.modifyNews(newsModified);
                if (count > 0) {
                    System.out.println("新闻修改成功,nid=" + newsModified.getNid());
                    request.setAttribute("modifyNews_msg", "新闻修改成功,nid=" + newsModified.getNid());
                } else {
                    System.out.println("新闻修改失败");
                    request.setAttribute("modifyNews_msg", "新闻修改失败,nid=" + newsModified.getNid());
                }
                //修改完成后跳转到新闻编辑页面
                request.getRequestDispatcher("/adminServlet/news?method=showNewsDetailsByNid&nid=" + newsModified.getNid()).forward(request, response);
            } else if (method.equals("deleteComments")) {//删除评论
                String cid = request.getParameter("cid");
                String nid = request.getParameter("nid");
                int count = commentsServices.deleteComments(Integer.parseInt(cid), Integer.parseInt(nid));
                if (count > 0) {
                    System.out.println("评论删除成功,cid=" + cid);
                    request.setAttribute("deleteComments_msg", "评论删除成功,cid=" + cid);
                } else {
                    System.out.println("cid=" + cid + "的评论不存在,删除失败");
                    request.setAttribute("deleteComments_msg", "cid=" + cid + "的评论不存在,删除失败");
                }
                //修改完成后跳转到新闻编辑页面
                request.getRequestDispatcher("/adminServlet/news?method=showNewsDetailsByNid&nid=" + nid).forward(request, response);
            } else if (method.equals("addNews")) {//添加新的新闻
                Map parameterMap = request.getParameterMap();
                News addedNews = new News();
                BeanUtils.populate(addedNews, parameterMap);
                //添加创建时间和最后一次修改时间到News对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = sdf.format(new Date());
                addedNews.setNcreateDate(date);
                addedNews.setNmodifyDate(date);
                //进入服务层添加新闻
                int count = newsServices.addNews(addedNews);
                if (count > 0) {
                    System.out.println("新闻添加成功");
                    request.setAttribute("addNews_msg", "新闻添加成功");
                } else {
                    System.out.println("新闻添加失败");
                    request.setAttribute("addNews_msg", "新闻添加失败");
                }
                //修改完成后跳转到新闻编辑页面
                request.getRequestDispatcher("/adminServlet/news?method=getAllTopic").forward(request, response);
            } else if (method.equals("deleteNews")) {//删除新闻
                String nid = request.getParameter("nid");
                int count = newsServices.deleteNewsByNid(Integer.parseInt(nid));
                if (count > 0) {
                    System.out.println("新闻删除成功,nid=" + nid);
                    request.setAttribute("deleteNews_msg", "新闻删除成功,nid=" + nid);
                } else {
                    System.out.println("nid=" + nid + "的新闻已不存在，删除失败");
                    request.setAttribute("deleteNews_msg", "新闻删除失败");
                }
                request.getRequestDispatcher("/adminServlet/news?method=getNewsByPage&pageNo=1&size=10&tid=0").forward(request, response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
